/*
 * Project Name spring-boot-tools
 * File Name MsgHead
 * Package Name com.huxiaosu.tools.cmpp.model
 * Create Time 2024/4/20
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp.model;

import lombok.Data;
import lombok.ToString;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

/**
 * 消息头(所有消息公共包头)
 *
 * @author liujie
 * @date 2024/4/20 10:00
 */
@Data
@ToString
public class MessageHeader {

    /**
     * Unsigned Integer 消息总长度
     */
    private int totalLength;

    /**
     * Unsigned Integer 命令类型
     */
    private int commandId;

    /**
     * Unsigned Integer 消息流水号,顺序累加,步长为1,循环使用（一对请求和应答消息的流水号必须相同）
     */
    private int sequenceId;

    public MessageHeader() {

    }

    public MessageHeader(int totalLength, int commandId, int sequenceId) {
        this.totalLength = totalLength;
        this.commandId = commandId;
        this.sequenceId = sequenceId;
    }

    public byte[] toBytes() {
        ByteArrayOutputStream bous = new ByteArrayOutputStream();
        DataOutputStream dous = new DataOutputStream(bous);
        try {
            dous.writeInt(this.getTotalLength());
            dous.writeInt(this.getCommandId());
            dous.writeInt(this.getSequenceId());
            dous.close();
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return bous.toByteArray();
    }

}
